<?php


namespace app\data\service;


use app\data\model\DataEnterpriseExtension;
use app\data\model\DataEnterpriseFreePolicy;
use app\data\model\DataEnterprisePolicyRelation;
use app\data\model\DataMsjx;
use app\data\model\DataNoticePushLog;
use app\data\model\DataPolicyExtension;
use app\data\model\DataPolicyInformation;
use app\data\model\DataQiyeRzinfo;
use app\data\model\DataQiyeXinxiku;
use think\admin\Service;
use app\data\model\DataPolicyItem;

/**
 * 政策服务层
 * Class PolicyService
 * @package app\data\service
 */
class PolicyService extends Service
{
    /**
     * @param $policyList
     * @param $policyId
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function addPolicyItem($policyList, $policyId): int
    {
        //先删除现有的所有数据  再插入
        DataPolicyItem::query()->where('policy_id', $policyId)->delete();
        if (empty($policyList)) {
            return 0;
        }
        $insertArr = [];
        foreach ($policyList as $item) {
            $insertArr[] = [
                'content'   => $item,
                'policy_id' => $policyId,
            ];
        }
        return DataPolicyItem::insertAll($insertArr);
    }

    public function enterpriseBandPolicy($enterpriseIds, $policyId, $req)
    {

        // if ($enterpriseIds === '') {
        //     $tags = $req['tags'] ?? '';
        //     if (!$tags) {
        //         return;
        //     }
        //     $enterpriseList = DataQiyeXinxiku::query();
        //     if ($tags = $tags ? explode(',', $tags) : null) {
        //         $row = '(';
        //         foreach ($tags as $tag) {
        //             // $enterpriseList = $enterpriseList->whereFindInSet('qybq', $tag);
        //             $row .= "find_in_set('{$tag}',qybq) or ";
        //         }
        //         $row            = rtrim($row, 'or ');
        //         $row            .= ')';
        //         $enterpriseList = $enterpriseList->whereRaw($row);
        //     }
        //     $enterpriseList   = $enterpriseList->where('status', 1)->select()->toArray();
        //     $reqEnterpriseIds = array_column($enterpriseList, 'id');
        // } else {
        //     $reqEnterpriseIds = explode(',', $enterpriseIds);
        // }
        $reqEnterpriseIds = explode(',', $enterpriseIds);
        if (!$reqEnterpriseIds) {
            return;
        }
        //根据企业id查询已经认证过的所有用户
        $authUser         = DataQiyeRzinfo::query()->whereIn('qrxxk_id', $reqEnterpriseIds)->select()->toArray();
        $noticeInsertData = $freePolicyInsertData = [];
        $policyInfo       = DataMsjx::query()->where('id', $policyId)->find();
        if (!$policyInfo) {
            return;
        }
        //添加提示记录
        foreach ($authUser as $item) {
            $exists = DataNoticePushLog::query()->where('user_id', $item['user_id'])->where('policy_id', $policyId)->find();
            //已存在的提示不再重复添加
            if ($exists) {
                continue;
            }
            $noticeInsertData[] = [
                'user_id'   => $item['user_id'],
                'title'     => $policyInfo->title,
                'content'   => $policyInfo->content,
                'type'      => DataNoticePushLog::NOTICE_TYPE_FREE_POLICY,
                'url'       => 'api/msjx/getMsjxInfo',
                'policy_id' => $policyId,
            ];
        }
        NoticeService::instance()->batchCreateNotice($noticeInsertData);
        // 生成待兑付记录
        foreach ($reqEnterpriseIds as $enterpriseId) {
            if (DataEnterpriseFreePolicy::query()->where('enterprise_id', $enterpriseId)
                ->where('policy_id', $policyId)
                ->where('policy_item_id', $req['id'])->find()) {
                continue;
            }
            $freePolicyInsertData[] = [
                'enterprise_id'  => $enterpriseId,
                'policy_id'      => $policyId,
                'policy_item_id' => $req['id'],
            ];
        }
        DataEnterpriseFreePolicy::insertAll($freePolicyInsertData);
    }

    public function getPolicyListByPolicyId($policyId): array
    {
        if (!$policyId) {
            return [];
        }
        return DataPolicyItem::query()->where('policy_id', $policyId)->select()->toArray();
    }

    public function handleExtended($params): void
    {
        $extended = $params['extension'] ?? [];
        if (!$extended) {
            return;
        }
        $insertData = [];
        $typeMap    = DataPolicyInformation::$fieldMap;
        foreach ($extended as $key => $val) {
            if (!isset($typeMap[$key])) {
                continue;
            }
            $info = DataPolicyExtension::query()->where('policy_id', $params['id'])
                ->where('policy_information_type', $typeMap[$key])
                ->find();
            if ($info) {
                $info->id_set = $val;
                $info->save();
                continue;
            }
            $insertData[] = [
                'policy_id'               => $params['id'],
                'policy_information_type' => $typeMap[$key],
                'id_set'                  => $val,
                'status'                  => 1,
            ];
        }
        $year     = $params['year'];
        $yearData = [
            'policy_id'               => $params['id'],
            'policy_information_type' => 12,
            'id_set'                  => 0,
            'status'                  => 1,
        ];
        if ($year === 1) {
            $yearData['id_set'] = $extended['year_start'] ?? 1 . ',' . $extended['year_end'] ?? 2;
        }
        $info = DataPolicyExtension::query()->where('policy_id', $params['id'])
            ->where('policy_information_type', 12)
            ->find();
        if ($info) {
            $info->id_set = $yearData['id_set'];
            $info->save();
        } else {
            $insertData[] = $yearData;
        }
        if ($insertData) {
            DataPolicyExtension::insertAll($insertData);
        }
    }

    public function createNoticeLog(array $data)
    {
        // 根据政策库的企业标签推送到企业信息消息
        $tag = $data['qybq'] ?? '';
        // 获取所有符合条件的企业 ID
        $enterpriseIds = [];
        if (!empty($tag)) {
            $tags = explode(',', $tag);
            foreach ($tags as $t) {
                $enterpriseIds = array_merge($enterpriseIds, DataQiyeXinxiku::whereFindInSet('qybq', $t)->column('id'));
            }
        }
        //处理扩展字段的匹配信息
        $extended = $data['extended'] ?? [];
        if ($extended) {
            foreach ($extended as $key => $val) {
                if ($val === '') {
                    continue;
                }
                $v                  = explode(',', $val);
                $queryEnterpriseIds = DataEnterpriseExtension::query()
                    ->where('policy_information_type', DataPolicyInformation::$fieldMap[$key])
                    ->whereIn('value', $v)
                    ->column('enterprise_id');
                if ($queryEnterpriseIds) {
                    $enterpriseIds = array_merge($enterpriseIds, $queryEnterpriseIds);
                }
            }

            if ($data['year'] == 2) {
                $queryEnterpriseIds = DataEnterpriseExtension::query()
                    ->where('policy_information_type', 12)
                    ->where('value', '>', 0)
                    ->column('enterprise_id');
            } else {
                $queryEnterpriseIds = DataEnterpriseExtension::query()
                    ->where('policy_information_type', 12)
                    ->whereBetween('value', $extended['year_start'] ?? 1, $extended['year_end'] ?? 2)
                    ->column('enterprise_id');
            }
            $enterpriseIds = array_merge($enterpriseIds, $queryEnterpriseIds);
        }
        // 获取所有的企业id
        if ($enterpriseIds) {
            // 去重企业 ID
            $uniqueEnterpriseIds = array_unique($enterpriseIds);
            sort($uniqueEnterpriseIds);
            // 获取已认证用户列表
            $certifiedUserList = DataQiyeRzinfo::query()->whereIn('qrxxk_id', $uniqueEnterpriseIds)->select()->toArray();
            // 初始化插入数据
            $insertData = $noticeInsertData = [];
            // 遍历已认证用户列表
            foreach ($certifiedUserList as $item) {
                $existingRelation = DataEnterprisePolicyRelation::query()->where([
                    'enterprise_id' => $item['qrxxk_id'],
                    'user_id'       => $item['user_id'],
                    'policy_id'     => $data['id'],
                ])->find();
                if (!$existingRelation) {
                    $insertData[]       = [
                        'enterprise_id' => $item['qrxxk_id'],
                        'user_id'       => $item['user_id'],
                        'policy_id'     => $data['id'],
                    ];
                    $noticeInsertData[] = [
                        'user_id'   => $item['user_id'],
                        'title'     => $data['title'],
                        'content'   => $data['content'],
                        'type'      => DataNoticePushLog::NOTICE_TYPE_NEW_POLICY,
                        'url'       => '/api/index/getZckInfo',
                        'policy_id' => $data['id'],
                    ];
                }
            }
            // 批量添加未读数据
            if (!empty($insertData)) {
                DataEnterprisePolicyRelation::insertAll($insertData);
            }
            if (!empty($noticeInsertData)) {
                NoticeService::instance()->batchCreateNotice($noticeInsertData);
            }
        }

    }
}
